from rest_framework import serializers
from django_redis import get_redis_connection
import logging

logger = logging.getLogger('meiduo')

class RegisterSmscodeSerializer(serializers.Serializer):
    text = serializers.CharField(label='验证码',max_length=4,min_length=4,required=True)
    image_code_id = serializers.UUIDField(label='验证图片ID',required=True)

    def validate(self, attrs):

        redis = get_redis_connection('code')

        sms_redis = redis.get('img_%s'%attrs['image_code_id'])

        if sms_redis is None:
            raise serializers.ValidationError('验证码已过期')

        try:
            redis.delete('img_%s'%attrs['image_code_id'])
        except Exception as e:
            logger.error(e)

        if sms_redis.decode().lower() != attrs['text'].lower():
            raise  serializers.ValidationError('验证码输入错误')

        return attrs


